package nosgoth.com.freecomm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class LoginActivity extends Activity implements OnEditorActionListener {
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // check if session id is set in application data, if so 
        // switch to main activity
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
		if (prefs.getString("SESSION", "") != "")
		{
			Intent freecommIntent = new Intent(this, FreecommActivity.class);
            startActivity(freecommIntent);
            return;
		}
		
		// no session, open login activity
		setContentView(R.layout.login);
        
        // create listener for input text box
        EditText txtUsername = (EditText)findViewById(R.id.txtUsername);
        if (txtUsername != null)
        	txtUsername.setOnEditorActionListener(this);
        
    }

	@Override
	public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
		
		// Call login page on server side
		EditText editText = (EditText)findViewById(R.id.txtUsername);
		new LoginTask().execute(editText.getText().toString());
		
		return false;
	}
	
	private class LoginTask extends AsyncTask<String, Void, Boolean> {
	    /** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
	    protected Boolean doInBackground(String... params) {
	    	try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet("http://lukasiak.dyndns.info/freecomm/login.php?username=" + params[0]);
				HttpResponse response = httpClient.execute(httpGet);
				BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				String line = rd.readLine();
				rd.close();
								
				if (line == "ERROR")
					return false;
				
				SharedPreferences prefs = getPreferences(MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("SESSION", line);
				editor.commit();
				
				return true;
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
	    }
	    
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    protected void onPostExecute(Boolean result) {
	    	if (result)
	    	{
	    		EditText editText = (EditText)findViewById(R.id.txtUsername);
	    		Intent freecommIntent = new Intent(editText.getContext(), FreecommActivity.class);
	            startActivity(freecommIntent);
	    	}
	    }
	}
}


